//首先引入这个方法
import JSEncrypt from 'jsencrypt'
// 公钥key
const publicKey = `
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHo5WgbTQTkIecdC6Mb/CTcaaJ
s5Kcc+NWm1Fp8WUr11HZFtr7+kUmDRvcJQ4k4b3xQWSvLK3AII1c482Wi601jHAb
Rc7b5mtCcQUs452ViuEBYnzj6MFgm60M5XaFCg2uy/b/aqkDp0Si5yF/NOht56eL
9gZxgNBA0Sf1wJzRkQIDAQAB
-----END PUBLIC KEY-----`
// 私钥key
const privateKey = `
-----BEGIN PRIVATE KEY-----
MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIejlaBtNBOQh5x0
Loxv8JNxpomzkpxz41abUWnxZSvXUdkW2vv6RSYNG9wlDiThvfFBZK8srcAgjVzj
zZaLrTWMcBtFztvma0JxBSzjnZWK4QFifOPowWCbrQzldoUKDa7L9v9qqQOnRKLn
IX806G3np4v2BnGA0EDRJ/XAnNGRAgMBAAECgYA8CNR+KDeHfU34mpfLwvP5XrE2
e4ulwclamO5E9PoxmGD6tBoCszgN6nltS91hx6S5dpcozZ6tzfqjpZRmULY9uwsa
YPFMpAzvM4jH0BjE6w0kfRGJ706d5GleuVscz0qHavnnoOLsJURF8W51vc63ENED
rTA/rywwIEnxV5ybjQJBAMVt3mVD6jpbJqFQPexQ9GmWVKv4xLKAb+iUc/xOWOy1
shTvnzqv3tJywl3pp2+QPF/qF7MGsdJ7Kgd65JIilSMCQQCv4PHH6ese3AA8it5H
NW1aSTRyVJRD62AsdiDXxbAGcEuH2FbsKZGhP75LvIg1AAmAiau8mwrny8nsNZ4p
zyu7AkAj0L+knUJzna+PWhAxu6nrMbNgkzuTqksi5TN5VPk6z+djdujq65a/lMP/
53BRg9gACmaMOq2tolxIiRnIDPADAkA0+7/6qJZjKoWLt430x7yUqV76Xk54E41a
d4+3UN+RYPzwBJVS+cbcW9aY/EfQJ521MkQhQlfLspG27gQitj2HAkA/rniKZ947
jn0dtM78/lco20waltUeCmR0rNns8qhfipXLH8sAfyUCm3cPvmnVZJ7iNxuJAYcu
x5YjRnl9etSp
-----END PRIVATE KEY-----`
//这里为分段加解密  也就是encryptLong 和 decryptLong 方法
///
// 16进制转byte数组

function hexToBytes(hex) {
  for (var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16))
  return bytes
}

// byte数组转16进制

function bytesToHex(bytes) {
  for (var hex = [], i = 0; i < bytes.length; i++) {
    hex.push((bytes[i] >>> 4).toString(16))
    hex.push((bytes[i] & 0xf).toString(16))
  }
  return hex.join('')
}

/**
 * Returns the pem encoded representation of the public key
 * If the key doesn't exists a new key will be created
 * @returns {string} pem encoded representation of the public key WITHOUT header and footer
 * @public
 */
JSEncrypt.prototype.encryptLong = function (string) {
  var k = this.getKey()
  try {
    var ct = '' //RSA每次加密最大117bytes，需要辅助方法判断字符串截取位置
    //1.获取字符串截取点
    var bytes = new Array()
    bytes.push(0)
    var byteNo = 0
    var len, c
    len = string.length
    var temp = 0
    for (var i = 0; i < len; i++) {
      c = string.charCodeAt(i)
      if (c >= 0x010000 && c <= 0x10ffff) {
        byteNo += 4
      } else if (c >= 0x000800 && c <= 0x00ffff) {
        byteNo += 3
      } else if (c >= 0x000080 && c <= 0x0007ff) {
        byteNo += 2
      } else {
        byteNo += 1
      }
      if (byteNo % 117 >= 114 || byteNo % 117 == 0) {
        if (byteNo - temp >= 114) {
          bytes.push(i)
          temp = byteNo
        }
      }
    }

    //2.截取字符串并分段加密
    if (bytes.length > 1) {
      for (var i = 0; i < bytes.length - 1; i++) {
        var str
        if (i == 0) {
          str = string.substring(0, bytes[i + 1] + 1)
        } else {
          str = string.substring(bytes[i] + 1, bytes[i + 1] + 1)
        }
        var t1 = k.encrypt(str)
        ct += t1
      }
      if (bytes[bytes.length - 1] != string.length - 1) {
        var lastStr = string.substring(bytes[bytes.length - 1] + 1)
        ct += k.encrypt(lastStr)
      }
      return hexToBytes(ct)
    }
    var t = k.encrypt(string)
    var y = hexToBytes(t)
    return y
  } catch (ex) {
    return false
  }
}
// utf-8数组转字符串
function utf8ByteToUnicodeStr(utf8Bytes) {
  var unicodeStr = ''
  for (var pos = 0; pos < utf8Bytes.length; ) {
    var flag = utf8Bytes[pos]
    var unicode = 0
    if (flag >>> 7 === 0) {
      unicodeStr += String.fromCharCode(utf8Bytes[pos])
      pos += 1
    } else if ((flag & 0xfc) === 0xfc) {
      unicode = (utf8Bytes[pos] & 0x3) << 30
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 24
      unicode |= (utf8Bytes[pos + 2] & 0x3f) << 18
      unicode |= (utf8Bytes[pos + 3] & 0x3f) << 12
      unicode |= (utf8Bytes[pos + 4] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 5] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 6
    } else if ((flag & 0xf8) === 0xf8) {
      unicode = (utf8Bytes[pos] & 0x7) << 24
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 18
      unicode |= (utf8Bytes[pos + 2] & 0x3f) << 12
      unicode |= (utf8Bytes[pos + 3] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 4] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 5
    } else if ((flag & 0xf0) === 0xf0) {
      unicode = (utf8Bytes[pos] & 0xf) << 18
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 12
      unicode |= (utf8Bytes[pos + 2] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 3] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 4
    } else if ((flag & 0xe0) === 0xe0) {
      unicode = (utf8Bytes[pos] & 0x1f) << 12
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 2] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 3
    } else if ((flag & 0xc0) === 0xc0) {
      //110
      unicode = (utf8Bytes[pos] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 1] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 2
    } else {
      unicodeStr += String.fromCharCode(utf8Bytes[pos])
      pos += 1
    }
  }
  return unicodeStr
}
/**
 * Returns the pem encoded representation of the public key
 * If the key doesn't exists a new key will be created
 * @returns {string} pem encoded representation of the public key WITHOUT header and footer
 * @public
 */
JSEncrypt.prototype.decryptLong = function (string) {
  var k = this.getKey()
  var MAX_DECRYPT_BLOCK = 128 //分段解密最大长度限制为128字节
  try {
    var ct = ''
    var t1
    var bufTmp
    var hexTmp
    var str = bytesToHex(string) //这块可能有些没有必要，因为sting参数已经及转为byte数组
    var buf = hexToBytes(str)
    var inputLen = buf.length
    //开始长度
    var offSet = 0
    //结束长度
    var endOffSet = MAX_DECRYPT_BLOCK

    //分段解密
    while (inputLen - offSet > 0) {
      if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
        bufTmp = buf.slice(offSet, endOffSet)
        hexTmp = bytesToHex(bufTmp)
        t1 = k.decrypt(hexTmp)
        ct += t1
        console.log('分段' + offSet)
        console.log(hexTmp)
        console.log(t1)
      } else {
        bufTmp = buf.slice(offSet, inputLen)
        hexTmp = bytesToHex(bufTmp)
        t1 = k.decrypt(hexTmp)
        ct += t1
        console.log('分段' + offSet)
        console.log(hexTmp)
        console.log(t1)
      }
      offSet += MAX_DECRYPT_BLOCK
      endOffSet += MAX_DECRYPT_BLOCK
    }
    return ct
  } catch (ex) {
    return false
  }
}
//
export default {
  /* JSEncrypt加密 */
  encrypt(params) {
    let data = JSON.stringify(params)
    var jsencrypt = new JSEncrypt()
    console.log(jsencrypt)
    jsencrypt.setPublicKey(publicKey)
    var result = jsencrypt.encryptLong(data)
    console.log('加密前： ', params, '加密后： ', result)
    return result
  },
  /* JSEncrypt解密 */
  decrypt(data) {
    var jsencrypt = new JSEncrypt()
    jsencrypt.setPrivateKey(privateKey)
    var result = jsencrypt.decryptLong(data)
    return result
  },
}
